package com.justspeak;

import com.justspeak.mediaplayer.MediaFileInfo;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.SeekBar;

/**
 * 课程学习界面
 */
public class LearningActivity extends Activity implements
		SurfaceHolder.Callback, Callback {
	private String TAG = "LearningActivity";
	private MediaPlayer mediaPlayer = null;
	private SurfaceView videosurface = null;
	private SurfaceHolder videoSurfaceHolder = null;
	private SeekBar seekbar = null;
	private MediaFileInfo mfi = new MediaFileInfo("/sdcard/mp4/test.mp4");
	private static final int MESSAGE_SEEKBAR_CHANGED = 1;
	private Handler handler = new Handler(this);
	private int duration = 0;
	private SeekProgress seekbar_trd = null;
	private boolean seeked = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_learning);
		seekbar = (SeekBar) findViewById(R.id.seekbar);
		init();
		videosurface = (SurfaceView) findViewById(R.id.surfaceview_videoplayer);
		videoSurfaceHolder = videosurface.getHolder();
		videoSurfaceHolder.addCallback(this);
		videoSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		seekbar_trd = new SeekProgress();
		seekbar_trd.setDaemon(false);

	}

	public void onDestroyed() {
		super.onDestroy();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		seekbar_trd.stopit();
	}

	private void init() {
		seekbar
				.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
					}

					public void onStartTrackingTouch(SeekBar seekBar) {
					}

					public void onStopTrackingTouch(SeekBar seekBar) {
						int changed = seekBar.getProgress();
						seeked = true;
						mediaPlayer.seekTo(changed);
						// seekBar.setProgress(changed);
					}
				});
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		playVideo(mfi);
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub

	}

	private void playVideo(MediaFileInfo mfi) {
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mediaPlayer.setDisplay(videoSurfaceHolder);
		try {
			// mediaPlayer.setDataSource(mfi.getFilePath());
//			mediaPlayer
//					.setDataSource(
//							this,
//							Uri
//									.parse("http://cslanguage.com/UserFiles/Blog/tdrmusic/UploadFiles/20111015022554988.mp3"));
			Uri path = Uri.parse("android.resource://" + this.getPackageName() + "/"
				    + R.raw.test);

				mediaPlayer.setDataSource(this, path);
			mediaPlayer.prepare();
			duration = mediaPlayer.getDuration();
			seekbar.setMax(duration);
			mediaPlayer.start();
			seekbar_trd.start();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					public void onCompletion(MediaPlayer mp) {
						synchronized (mediaPlayer) {
							mediaPlayer.release();
							finish();
						}
					}
				});
	}

	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MESSAGE_SEEKBAR_CHANGED:
			if (seeked) {
				seeked = false;
				return true;
			}
			int time = msg.arg1;
			seekbar.setProgress(time);
			return true;
		}
		return true;
	}

	private class SeekProgress extends Thread {
		int current = 0;
		boolean stopped = false;

		public void stopit() {
			stopped = true;
		}

		public void run() {

			current = mediaPlayer.getCurrentPosition();
			while (!stopped && mediaPlayer != null && current <= duration) {
				Message msg = Message.obtain();
				msg.what = MESSAGE_SEEKBAR_CHANGED;
				msg.arg1 = current;
				handler.sendMessage(msg);
				if (mediaPlayer != null) {
					try {
						synchronized (mediaPlayer) {
							if (mediaPlayer != null && mediaPlayer.isPlaying()) {
								current = mediaPlayer.getCurrentPosition();
							}
						}
					} catch (Exception e) {
						current = msg.arg1;
					}
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Log.e(TAG, e.getMessage());
				}
			}
			if (stopped) {
				if (mediaPlayer != null) {
					try {
						mediaPlayer.stop();
						mediaPlayer.release();
						mediaPlayer = null;
					} catch (Exception e) {
						Log.e(TAG, "onPause exception....." + e.getMessage());
					}
				}
			}
		}
	}
}
